package lv.ante.xwiki.latex;

import java.io.File;
import java.io.IOException;

import lv.ante.xwiki.cli.CommandLineExecutor;
import lv.ante.xwiki.cli.LineResponseHandler;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.api.Api;


public class LatexPluginApi extends Api {

	private static Log log = LogFactory.getLog(LatexPluginApi.class);
	private LatexPlugin plugin;

	public static String hashCode;

	public static Object lock = new Object();

	public LatexPluginApi(LatexPlugin plugin, XWikiContext context) {
		super(context);
		setPlugin(plugin);
	}

	public LatexPlugin getPlugin() {
		// return (hasProgrammingRights() ? plugin : null);
		// Uncomment for allowing unrestricted access to the plugin
		return plugin;
	}

	public void setPlugin(LatexPlugin plugin) {
		this.plugin = plugin;
	}

	protected static String img(String expr, String[] cmdLine) {
		
		if (cmdLine == null) {
			cmdLine = new String[] { "/usr/bin/texvc", "/tmp",
					"/var/www/latex", expr, "UTF-8" };
		}
		hashCode = Digest.getInstance().getDigest(expr);
		File f = new File("/var/www/latex/" + hashCode + ".png");
		if (f.exists()) {
			return "<span class='math'><img src='http://www.ante.lv/latex/" + hashCode
			+ ".png' alt='" + expr + "'/></span>";
		}

		synchronized (lock) {
			CommandLineExecutor executor = new CommandLineExecutor(
					new LineResponseHandler() {
						@Override
						public void handle(String line) {
							log.debug("{STDOUT}" + line);
							if (line != null && line.length() >= 33) {
								hashCode = line.substring(1, 33);
							}
						}
					}, new LineResponseHandler() {

						@Override
						public void handle(String line) {
							// ignore
						}
					});
			try {
				executor.execute(cmdLine);
				int exitVal = executor.close();

				log.debug("exitVal = " + exitVal);
			} catch (IOException e) {
				e.printStackTrace(System.err);
				log.error("Error executing texvc", e);
			}
		}

		return "<span class='math'><img src='http://www.ante.lv/latex/" + hashCode
				+ ".png' alt='" + expr + "'/></span>";

	}

	public String image(String expr) {
		return img(expr, null);
	}

	public void updatePage() {
		// ...
	}

}
